package visiopuce;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.exception.GenericJDBCException;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
	private static final SessionFactory sessionFactory;
	private static ServiceRegistry serviceRegistry;

	static {
		try {
			// Create the SessionFactory from hibernate.cfg.xml
			Configuration configuration = new Configuration();
			configuration.configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Throwable ex) {
			// Log the exception.
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}

	}

	public static Session beginTransaction() {
		Session hibernateSession = null;
		try {
			hibernateSession = HibernateUtil.getSession();
			hibernateSession.beginTransaction();
		} catch (GenericJDBCException ex) {
			MessageDialog.openError(Display.getCurrent().getActiveShell(), "Erreur sur la base de données", ex.getMessage() + "(" + ex.getErrorCode() + " : " + ex.getCause() + ")");
		}
		return hibernateSession;
	}

	public static void closeSession() {
		HibernateUtil.getSession().close();
	}

	public static void commitTransaction() {
		if (!HibernateUtil.getSession().getTransaction().wasCommitted()) {
			HibernateUtil.getSession().getTransaction().commit();
		}
	}

	public static Session getSession() {
		Session hibernateSession = sessionFactory.getCurrentSession();
		return hibernateSession;
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void rollbackTransaction() {
		HibernateUtil.getSession().getTransaction().rollback();
	}
}